export interface ParsedRoomLine {
  lineNumber: number;
  raw: string;
  roomId: string;
  title: string | null;
  streamerName: string | null;
}

export interface ParseError {
  lineNumber: number;
  raw: string;
  message: string;
}

export interface ParseRoomsResult {
  entries: ParsedRoomLine[];
  errors: ParseError[];
}

const sanitize = (value: string | undefined): string | null => {
  if (!value) return null;
  const trimmed = value.trim();
  return trimmed.length > 0 ? trimmed : null;
};

export const parseRoomImportText = (content: string): ParseRoomsResult => {
  const entries: ParsedRoomLine[] = [];
  const errors: ParseError[] = [];
  const seenIds = new Set<string>();

  if (!content || content.trim().length === 0) {
    return { entries, errors };
  }

  const lines = content.split(/\r?\n/);

  lines.forEach((line, index) => {
    const raw = line.trim();
    const lineNumber = index + 1;

    if (!raw) {
      return;
    }

    const segments = raw.split(',').map(segment => segment.trim());
    const roomId = sanitize(segments[0]);

    if (!roomId) {
      errors.push({ lineNumber, raw, message: '缺少房间号' });
      return;
    }

    if (seenIds.has(roomId)) {
      errors.push({ lineNumber, raw, message: '文件中重复的房间号' });
      return;
    }
    seenIds.add(roomId);

    const title = sanitize(segments[1]);
    const extraSegments = segments.slice(2);
    const streamerName = sanitize(extraSegments.length > 0 ? extraSegments.join(',') : undefined);

    entries.push({ lineNumber, raw, roomId, title, streamerName });
  });

  return { entries, errors };
};

export const readTextFile = (file: File): Promise<string> => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => resolve(typeof reader.result === 'string' ? reader.result : '');
    reader.onerror = () => reject(reader.error ?? new Error('读取文件失败'));
    reader.readAsText(file, 'utf-8');
  });
};
